#!/bin/bash

# 设置变量
APP_NAME="goout-server"
REMOTE_USER="root"
REMOTE_HOST="host.tangyujun.com"
REMOTE_DIR="/root/apps/goout"
REMOTE_LOGS_DIR="${REMOTE_DIR}/logs"
BUILD_TIME=$(date '+%Y-%m-%d %H:%M:%S')
VERSION="1.0.0"

# 错误处理函数
handle_error() {
    echo "错误: $1"
    exit 1
}

echo "开始构建 ${APP_NAME}..."

# 构建Linux版本
GOOS=linux GOARCH=amd64 go build -ldflags "-X github.com/AiGenApps/goout-server/handlers.Version=${VERSION} -X 'github.com/AiGenApps/goout-server/handlers.BuildTime=${BUILD_TIME}'" -o ${APP_NAME}

if [ $? -ne 0 ]; then
    handle_error "构建失败"
fi

echo "构建成功"

# 创建部署目录结构
mkdir -p deploy
cp ${APP_NAME} deploy/
cp config/mongodb.go deploy/

# 创建服务文件
cat > deploy/${APP_NAME}.service << EOF
[Unit]
Description=GoOut Server
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=${REMOTE_DIR}
ExecStart=${REMOTE_DIR}/${APP_NAME}
StandardOutput=append:${REMOTE_LOGS_DIR}/app.log
StandardError=append:${REMOTE_LOGS_DIR}/error.log
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF

# 创建启动脚本
cat > deploy/start.sh << EOF
#!/bin/bash
set -e

# 创建并设置目录权限
mkdir -p ${REMOTE_DIR}
chmod 755 ${REMOTE_DIR}

# 创建日志目录
mkdir -p ${REMOTE_LOGS_DIR}
touch ${REMOTE_LOGS_DIR}/app.log
touch ${REMOTE_LOGS_DIR}/error.log
chmod 755 ${REMOTE_LOGS_DIR}
chmod 644 ${REMOTE_LOGS_DIR}/*.log

# 设置应用程序权限
chmod 755 ${APP_NAME}

# 停止并禁用旧服务
systemctl stop ${APP_NAME} || true
systemctl disable ${APP_NAME} || true

# 复制并启用新服务
cp ${APP_NAME}.service /etc/systemd/system/
chmod 644 /etc/systemd/system/${APP_NAME}.service

# 重新加载systemd并启动服务
systemctl daemon-reload
systemctl enable ${APP_NAME}
systemctl start ${APP_NAME}

# 输出服务状态
systemctl status ${APP_NAME}

# 设置日志轮转
cat > /etc/logrotate.d/${APP_NAME} << EOL
${REMOTE_LOGS_DIR}/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 644 root root
    postrotate
        systemctl restart ${APP_NAME}
    endscript
}
EOL

# 立即执行一次日志轮转（如果需要）
logrotate -f /etc/logrotate.d/${APP_NAME}
EOF

chmod +x deploy/start.sh

echo "正在推送到远程服务器..."

# 确保远程目录存在并设置权限
ssh ${REMOTE_USER}@${REMOTE_HOST} "mkdir -p ${REMOTE_DIR} && chmod 755 ${REMOTE_DIR}" || handle_error "创建远程目录失败"

# 先停止服务
ssh ${REMOTE_USER}@${REMOTE_HOST} "systemctl stop ${APP_NAME} || true"

# 分别传输文件
for file in deploy/*; do
    filename=$(basename "$file")
    echo "正在传输 $filename..."
    scp "$file" ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/ || handle_error "传输 $filename 失败"
done

echo "文件传输成功"

# 在远程服务器上执行启动脚本
echo "正在启动服务..."
ssh ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && bash start.sh" || handle_error "服务启动失败"

echo "部署完成"

# 清理本地构建文件
rm -rf deploy ${APP_NAME}

echo "清理完成"

# 显示最新日志
echo "显示最新日志..."
ssh ${REMOTE_USER}@${REMOTE_HOST} "tail -n 50 ${REMOTE_LOGS_DIR}/app.log"